package com.itheima.filter;

import com.itheima.utils.JwtUtils;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
@Slf4j
@WebFilter
public class LoginFilter implements Filter {
    // 拦截所有请求 判断token 是否正确 正确放行 不正确 返回错误信息
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        //获取请求路径
        String path = request.getRequestURI();

        // 判断是否是登录请求 是 放行
        if (path.contains("login")) {
            log.info("登录请求,放行");
            filterChain.doFilter(request, response);
            return;
        }

        // 获取token 判断token是否为null 是 返回错误信息401
        String token = request.getHeader("token");
        if (token == null || token.length()==0){
            log.info("token为空,返回401");
            response.setStatus(401);
            return;
        }

        //判断token是否正确 是 放行 不是 返回错误信息401
        try{
            JwtUtils.parseJWT(token);
        }catch (Exception e){
            log.info("token不正确,返回401");
            response.setStatus(401);
            return;
        }

        // 放行
        filterChain.doFilter(request, response);
    }
}
